﻿using System;
using System.Threading.Tasks;
using OS.Common.Enums;

namespace OS.Common.Plugs.LogPlug
{
    /// <summary>
    /// 日志工具
    /// </summary>
    public static class LogUtil
    {
        private static readonly DefaultLogPlug DefaultCache = new DefaultLogPlug();

        /// <summary>
        /// 通过模块获取日志模块实例
        /// </summary>
        /// <param name="logModule">日志模块</param>
        /// <returns></returns>
        private static ILogPlug GetLogWrite(string logModule)
        {
            if (string.IsNullOrEmpty(logModule))
            {
                logModule = "default";
            }

            Func<string, ILogPlug> logProvider = BaseConfig.LogProvider;
            return logProvider?.Invoke(logModule) ?? DefaultCache;
        }

        /// <summary>
        /// 记录信息
        /// </summary>
        /// <param name="msg"> 日志信息  </param>
        /// <param name="msgKey">  关键值  </param>
        /// <param name="moduleName"> 模块名称 </param>
        public static string Info(object msg, string msgKey = null, string moduleName = "default")
        {
            return Log(new LogInfo(LogLevelEnum.Info, msg, msgKey, moduleName));
        }

        /// <summary>
        /// 记录警告，用于未处理异常的捕获
        /// </summary>
        /// <param name="msg"> 日志信息  </param>
        /// <param name="msgKey">  关键值  </param>
        /// <param name="moduleName">模块名称</param>
        public static string Warning(object msg, string msgKey = null, string moduleName = "default")
        {
            return Log(new LogInfo(LogLevelEnum.Warning, msg, msgKey, moduleName));
        }

        /// <summary>
        /// 记录错误，用于捕获到的异常信息记录
        /// </summary>
        /// <param name="msg"> 日志信息  </param>
        /// <param name="msgKey">  关键值  </param>
        /// <param name="moduleName">模块名称</param>
        public static string Error(object msg, string msgKey = null, string moduleName = "default")
        {
            return Log(new LogInfo(LogLevelEnum.Error, msg, msgKey, moduleName));
        }

        /// <summary>
        /// 记录错误，用于捕获到的异常信息记录
        /// </summary>
        /// <param name="msg"> 日志信息  </param>
        /// <param name="msgKey">  关键值  </param>
        /// <param name="moduleName">模块名称</param>
        public static string Trace(object msg, string msgKey = null, string moduleName = "default")
        {
            return Log(new LogInfo(LogLevelEnum.Trace, msg, msgKey, moduleName));
        }

        /// <summary>
        ///   记录日志
        /// </summary>
        /// <param name="info"></param>
        private static string Log(LogInfo info)
        {
            if (string.IsNullOrEmpty(info.ModuleName))
            {
                info.ModuleName = "default";
            }
            ILogPlug logWrite = GetLogWrite(info.ModuleName);
            logWrite.SetLogCode(info);
            Task.Run(delegate
            {
                logWrite.WriteLog(info);
            });
            return info.LogCode;
        }
    }
}